// 认证服务
import { apiService } from './api'
import { userStorage } from '@/utils/storage'
import type { LoginRequest, LoginResponse, UserInfo } from '@/types'

export class AuthService {
  /**
   * 用户登录
   */
  async login(username: string, password: string, rememberMe = false): Promise<LoginResponse> {
    const request: LoginRequest = {
      username,
      password,
      rememberMe
    }

    return apiService.login(request)
  }

  /**
   * 用户注册
   */
  async register(registerData: { username: string; password: string; nickname: string; email: string; phone?: string }): Promise<UserInfo> {
    return apiService.register(registerData)
  }

  /**
   * 用户登出
   */
  async logout(): Promise<void> {
    return apiService.logout()
  }

  /**
   * 刷新Token
   */
  async refreshToken(): Promise<string> {
    return apiService.refreshToken()
  }

  /**
   * 获取当前用户信息
   */
  async getCurrentUser(): Promise<UserInfo> {
    return apiService.getCurrentUser()
  }

  /**
   * 检查用户是否已登录
   */
  isAuthenticated(): boolean {
    const token = userStorage.getToken()
    return !!token
  }

  /**
   * 验证Token是否有效
   */
  async validateToken(): Promise<boolean> {
    try {
      await this.getCurrentUser()
      return true
    } catch (error) {
      return false
    }
  }

  /**
   * 获取本地存储的用户信息
   */
  getStoredUserInfo(): UserInfo | unknown {
    return userStorage.getUserInfo()
  }

  /**
   * 获取本地存储的Token
   */
  getStoredToken(): string | null {
    return userStorage.getToken()
  }

  /**
   * 清除认证信息
   */
  clearAuth(): void {
    userStorage.clearUserData()
  }
}

export const authService = new AuthService()
